<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px;">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="6" >
              <a-form-item label="主机IP">
                <a-select
                  placeholder="请选择主机IP"
                  v-model="queryParam.ip"
                  style="width: 100%"
                  allow-clear
                  :showSearch="true"
                  @focus="queryEnableHostList"
                >
                  <a-select-option v-for="(d, index) in enableHostList" :key="index" :value="d.hostIp">{{ d.hostIp }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col>
              <span class="table-page-search-submitButtons" style="float: right;">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />刷新</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <!-- 增加文件夹 -->
      <wenjianjia-form
        :currentPath="currentPath"
        :ip="queryParam.ip"
        v-if="showWenjianjiaForm"
        ref="wenjianjiaForm"
        @ok="getList"
        @close="showWenjianjiaForm = false"
      />
      <!-- 增加文件 -->
      <wenjian-form
        :currentPath="currentPath"
        :ip="queryParam.ip"
        v-if="showWenjianForm"
        ref="wenjianForm"
        @ok="getList"
        @close="showWenjianForm = false"
      />
      <!-- 上传 -->
      <upload-form
        :currentPath="currentPath"
        :ip="queryParam.ip"
        v-if="showUploadForm"
        ref="uploadForm"
        @ok="getList"
        @close="showUploadForm = false"
      />
      <!-- 内容 -->
      <content-form
        :currentPath="currentPath"
        :ip="queryParam.ip"
        v-if="showContentForm"
        ref="contentForm"
        @close="showContentForm = false"
      />
      <!-- 重命名 -->
      <file-system-edit-form
        :currentPath="currentPath"
        :ip="queryParam.ip"
        v-if="showEditModal"
        ref="fileSystemEditForm"
        @ok="getList"
        @close="showEditModal = false"
      />
      <advance-table
        title=" "
        :scroll="{ y: 580 }"
        :pagination="{
          current: queryParam.pageNum,
          pageSize: 20,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange
        }"
        tableKey="base-fileSystem-index-table"
        @change="handleTableChange"
        rowKey="fileName"
        size="middle"
        @refresh="getList"
        :columns="columns"
        :data-source="fileSystemList"
        :loading="loading"
        :format-conditions="true"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
        <div class="table-operations" slot="button">
          <div style="float: left;">
            <a-icon type="home" />
            <span v-for="(path, index) in currentPathList" :key="index">
              <a class="breadcrumb" @click="breadcrumb_enter(path)">{{ path }}</a>
            </span>
          </div>
          <a-button type="primary" @click="handlAddWenjianjia">
            <a-icon type="folder-add" />新增文件夹
          </a-button>
          <a-button type="primary" @click="handlAddWenjian">
            <a-icon type="plus-square" />新增文件
          </a-button>
          <a-button type="primary" @click="handlUpload">
            <a-icon type="upload" />上传
          </a-button>
          <a-button type="primary" @click="handleDownload">
            <a-icon type="download" />下载
          </a-button>
          <!-- <a-button type="danger" :disabled="multiple" @click="handleDelete">
            <a-icon type="delete" />删除文件或文件夹
          </a-button> -->
        </div>
        <span slot="fileName" slot-scope="{record}">
          <span v-if="record.fileType === 'directory'">
            <span class="iconfont icon-size icon-wenjianjia_o" ></span>
            <a class="breadcrumb" @click="enterFolder(record)">{{ record.fileName }}</a>
          </span>
          <span v-if="record.fileType === 'regular_file'">
            <span class="iconfont icon-size icon-file" ></span>
            {{ record.fileName }}
          </span>
          <span v-if="record.fileType === 'symbolic_link'">
            <span class="iconfont icon-size icon-lianjie" ></span>
            {{ record.fileName }}
          </span>
        </span>
        <span slot="fileType" slot-scope="{record}">
          {{ fileTypeFormat(record) }}
        </span>
        <span slot="operation" slot-scope="{text, record}">
          <a @click="handleUpdate(record)" v-hasPermi="['dockerinsight:fileSystem:edit']">
            重命名
          </a>
          <a @click="getContent(record)" v-if="record.fileType==='regular_file'" >
            | 内容
          </a>
          <a @click="handleDelete(record)" v-hasPermi="['dockerinsight:fileSystem:remove']">
            | 删除
          </a>
        </span>
      </advance-table>
    </a-card>
  </div>
</template>
<script>
import { listFileSystem, getInitData, removeFile, download } from '@/api/dockerinsight/fileSystem'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import ContentForm from '@/views/dockerinsight/filesystem/modules/ContentForm'
import FileSystemEditForm from '@/views/dockerinsight/filesystem/modules/FileSystemEditForm'
import UploadForm from '@/views/dockerinsight/filesystem/modules/UploadForm.vue'
import WenjianjiaForm from '@/views/dockerinsight/filesystem/modules/WenjianjiaForm.vue'
import WenjianForm from '@/views/dockerinsight/filesystem/modules/WenjianForm.vue'
import { getEnalbeList } from '@/api/dockerinsight/host'
export default {
  name: 'FileSystem',
  components: {
    AdvanceTable,
    ContentForm,
    FileSystemEditForm,
    UploadForm,
    WenjianjiaForm,
    WenjianForm
  },
  data () {
    return {
      showUploadForm: false,
      showWenjianjiaForm: false,
      showWenjianForm: false,
      showContentForm: false,
      showEditModal: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 文件中心表格数据
      fileSystemList: [],
      // 类型字典
      fileTypeOptions: [],
      // 可用主机列表
      enableHostList: [],
      currentPathList: [],
      currentPath: '/',
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10
      },
      viewFileParam: {
      },
      columns: [
        {
          title: '文件名',
          dataIndex: 'fileName',
          scopedSlots: { customRender: 'fileName' },
          ellipsis: true,
          align: 'left',
          width: '22.5%'
        },
        {
          title: '修改时间',
          dataIndex: 'fileUpdateTime',
          ellipsis: true,
          sorter: true,
          align: 'left',
          width: '22.5%'
        },
        {
          title: '类型',
          dataIndex: 'fileType',
          scopedSlots: { customRender: 'fileType' },
          align: 'center',
          width: '22.5%'
        },
        {
          title: '大小',
          dataIndex: 'fileSize',
          ellipsis: true,
          align: 'left',
          width: '22.5%'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  created () {
    getInitData('fie_type').then(response => {
      this.fileTypeOptions = response.data.fie_type
    })
    this.queryEnableHostList()
    this.currentPathList = ['/']
  },
  methods: {
    /** 查询可用主机列表 */
    queryEnableHostList() {
      getEnalbeList().then(response => {
        this.enableHostList = response.data
      })
    },
    /** 查询文件中心列表 */
    getList () {
      this.loading = true
      listFileSystem(this.queryParam).then(response => {
        this.fileSystemList = response.data.list
        this.total = response.data.total
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    // 类型字典翻译
    fileTypeFormat (row) {
      if (row.fileType) {
        return this.selectDictLabel(this.fileTypeOptions, row.fileType)
      } else {
        return ''
      }
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10
      }
      this.selectedRowKeys = []
      this.selectedRows = []
      this.fileSystemList = []
    },
    /** 翻页操作 */
    onShowSizeChange (current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSizeChange (current, size) {
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = size
      this.getList()
    },
    /** 翻页操作 */
    changeSize (current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    // 新增文件夹
    handlAddWenjianjia () {
      this.showWenjianjiaForm = true
      this.$nextTick(() => (
        this.$refs.wenjianjiaForm.handleAdd()
      ))
    },
    // 新增文件
    handlAddWenjian () {
      this.showWenjianForm = true
      this.$nextTick(() => (
        this.$refs.wenjianForm.handleAdd()
      ))
    },
    // 上传文件
    handlUpload () {
      this.showUploadForm = true
      this.$nextTick(() => (
        this.$refs.uploadForm.handleUpload()
      ))
    },
    // 下载文件
    handleDownload () {
      const selectRowKeys = this.selectedRowKeys
      if (selectRowKeys.length === 0) {
        this.$message.info('请选择要下载的文件！')
        return
      }
      if (selectRowKeys.length > 1) {
        this.$message.info('每次只能下载一个文件!')
        return
      }
      var that = this
      this.$confirm({
        title: '确认下载所选中文件?',
        onOk () {
          const params = {}
          params.ip = that.queryParam.ip
          params.currentPath = that.currentPath
          params.fileName = selectRowKeys[0]
          return download(params)
            .then((res) => {
              // 获取filename，这里使用的是正则表达式，关联 辅助输出接口 的第9行
              // data中装的是文件体，需要使用Blob流可以下载
              const blob = new Blob([res])
              // 网上最常用的下载方法
              const downloadElement = document.createElement('a')
              const href = window.URL.createObjectURL(blob) // 创建下载的链接
              downloadElement.href = href
              downloadElement.download = params.fileName // 下载后文件名
              document.body.appendChild(downloadElement)
              downloadElement.click() // 点击下载
              document.body.removeChild(downloadElement) // 下载完成移除元素
              window.URL.revokeObjectURL(href) // 释放blob对象
              that.onSelectChange([], [])
              that.$message.success(
                '下载成功',
                3
              )
            })
        },
        onCancel () {}
      })
    },
    getContent (record) {
      this.showContentForm = true
      this.$nextTick(() => (
        this.$refs.contentForm.getContent(record.fileName)
      ))
    },
    handleUpdate (record) {
      this.showEditModal = true
      this.$nextTick(() => (
        this.$refs.fileSystemEditForm.handleUpdate(record)
      ))
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      var that = this
      const fileName = row.fileName
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk () {
          const params = {}
          params.fileName = fileName
          params.currentPath = that.currentPath
          params.ip = that.queryParam.ip
          return removeFile(params)
            .then(() => {
              that.onSelectChange([], [])
              that.getList()
              that.$message.success(
                '删除成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
    handleTableChange (pagination, filters, sorter) {
      if (sorter.field !== undefined && sorter.field !== null && sorter.field !== '') {
        this.queryParam.orderByColumn = sorter.field
        this.queryParam.isAsc = sorter.order
      }
      this.getList()
    },
    // 进入文件夹
    enterFolder (record) {
      if (record.fileType === 'directory') {
        this.currentPathList.push(record.fileName + '/')
        this.currentPath = this.currentPathList.join('')
        this.queryParam.path = this.currentPath
        this.getList()
      }
    },
    // 文件菜单进入
    breadcrumb_enter(path) {
      console.log(path)
      const arr = this.currentPathList
      const newArr = []
      for (let i = 0; i < arr.length; i++) {
        newArr.push(arr[i])
        if (arr[i] === path) {
          break
        }
      }
      this.currentPathList = newArr
      this.currentPath = newArr.join('')
      this.queryParam.path = this.currentPath
      this.getList()
    }
  }
}
</script>
<style lang="css" scoped>
.breadcrumb {
  color: rgba(52, 46, 46, 0.868);
  margin: 0 4px;
}
.breadcrumb:hover {
  color: #2f54eb;
  text-decoration: underline;
}
.breadcrumb-separator {
  color: rgba(52, 46, 46, 0.868);
  margin: 0 4px;
}
</style>
